<template>
  <div class="formTree">
    <div class="formSetting">
      <div class="title">
        <div class="block"></div>
        <div class="text">表单设计</div>
      </div>
      <div>
        <Button class="button" type="primary" @click="setAttribute">指标属性设置</Button>
      </div>
    </div>
    <div class="design">
      <FormBlock title="表单树" direction="column" class="left-area">
        <el-tree
          ref="tree"
          :data="treeData"
          empty-text="暂无数据"
          default-expand-all
          node-key="id"
          class="tree-box"
          icon-class="ivu-icon-ios-arrow-forward"
          highlight-current
          :draggable="true"
          :allow-drop="allowDrop"
          :render-content="renderContent"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </FormBlock>
      <FormBlock :title="treeInfoTitle" direction="column" class="right-area">
        <div class="treeInfo">
          <Form :model="treeInfoData" :disabled="isPreview" :rules="ruleValidate" ref="form" :label-width="100">
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="name" :label="'指标名称'">
                  <Input :disabled="isRootNode" @on-enter="save" v-model="treeInfoData.name" placeholder="请输入" />
                </Form-item>
              </Col>
            </Row>
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="tip" :label="'指标说明'">
                  <Input type="textarea" v-model="treeInfoData.tip" @on-enter="save" placeholder="请输入" />
                </Form-item>
              </Col>
            </Row>
            <Row class="code-row-bg">
              <Col span="16">
                <Form-item prop="weight" :label="'权重'">
                  <InputNumber
                    :disabled="isRootNode"
                    :active-change="false"
                    v-model="treeInfoData.weight"
                    placeholder="请输入权重"
                    :formatter="value => `${value}%`"
                    :parser="value => value.replace('%', '')"
                    />
                </Form-item>
              </Col>
            </Row>
            <div v-if="isLeaf || isAppend">
              <Row class="code-row-bg">
                <Col span="16">
                  <Form-item prop="tip" :label="'评分'">
                    <InputNumber
                      :precision="attributes.numberType!==3 ? attributes.numberType : 2"
                      :editable="true"
                      :value="null"
                      :active-change="false"
                      :formatter="value => attributes.numberType===3? `${value}%` : value"
                      placeholder="已设置评分"
                    ></InputNumber>
                  </Form-item>
                </Col>
              </Row>
              <Row class="code-row-bg">
                <Col span="16">
                  <Form-item prop="tip" :label="'评分说明'">
                    <Input placeholder="已设置评分说明" :maxlength="attributes.maxlength" />
                  </Form-item>
                </Col>
              </Row>
            </div>
            <Row style="margin: 15px 0">
              <Col span="16" style="transform: translateX(35%)">
                <RPButton optType="save" style="margin-left: 80px;" @click="save" />
              </Col>
            </Row>
          </Form>
        </div>
      </FormBlock>
    </div>
  </div>
</template>

<script>
import setAttribute from './components/setAttribute.vue'
import { addNodeToChildren, updateNode } from './utils'
import _ from 'lodash'
import { uuid } from 'vue-uuid'

export default {
  data() {
    return {
      treeInfoData: {
        name: '',
        tip: '',
        weight: null,
      },
      ruleValidate: {
        name: { required: true, message: '请输入指标名称', trigger: 'blur' },
        weight: { required: true, message: '请输入权重', type: 'number',  trigger: 'blur' }
      },
      isRootNode: false, // 根节点
      isLeaf: false,
      selectedId: '', // 选中的节点ID
      isAppend: false,
      treeInfoTitle: '',
      isDirty: false,
      attributes: {
        numberType: 0,
        scoreRequire: 1,
        type: 0,
        maxlength: 300,
        scoreDesReq: 0
      }, // 整个表单的属性设置（评分和评分说明）
    }
  },
  props: {
    treeData: {
      type: Array,
      default: () => []
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    checkResult: {
      type: String,
      default: null
    },
    attr: {
      type: Object,
      default: () => ({
        numberType: 0,
        scoreRequire: 1,
        type: 0,
        maxlength: 300,
        scoreDesReq: 1
      })
    }
  },
  methods: {
    renderContent(h, { node, data, store }) {
      let isRootNode = node.level == 1
      return h(
        'span',
        {
          style: {
            display: 'inline-block',
            width: '100%'
          },
          class: ['tree-row', data.selected ? 'tree-row-selected' : '', data.class]
        },
        [
          h('span', [
            h(
              'span',
              {
                class: 'ivu-tree-title',
                style: {
                  fontSize: '14px'
                },
                on: {
                  click: () => {
                    this.onNodeSelected(node, data)
                  }
                },
                attrs: {
                  title: data.label
                }
              },
              data.label
            ),
            data.id === this.checkResult ? h('span', {
              style: {
                'margin-left': '-60px',
                'color': 'red'
              }
            }, '子节点权重错误！'): ''
          ]),
          h(
            'span',
            {
              style: {
                display: 'inline-block',
                // position: "absolute",
                // right: "2px"
                width: '40px'
              }
            },
            [
              node.level < 5
                ? h(
                    'button',
                    {
                      props: Object.assign({}, this.buttonProps),
                      style: {
                        padding: '1px 3px',
                        borderRadius: '3px'
                      },
                      on: {
                        click: () => {
                          this.append(node, data)
                        }
                      }
                    },
                    [
                      h('i', {
                        class: 'el-icon-plus',
                        style: {
                          lineHeight: 1.5
                        }
                      })
                    ]
                  )
                : '',
              h(
                'button',
                {
                  props: Object.assign({}, this.buttonProps),
                  class: isRootNode ? 'rootNode' : '',
                  style: {
                    padding: '1px 3px 2px',
                    borderRadius: '3px'
                  },
                  on: {
                    click: () => {
                      this.remove(node, data, store)
                    }
                  }
                },
                [
                  h('i', {
                    class: 'el-icon-delete',
                    style: {
                      lineHeight: 1.5
                    }
                  })
                ]
              )
            ]
          )
        ]
      )
    },
    selectFirstNode() {
      if (!this.treeData.length) return
      this.$refs.tree.setCurrentNode(this.treeData[0])
      this.treeInfoData.name = this.treeData[0].label
      this.treeInfoData.tip = this.treeData[0].tip
      this.treeInfoData.weight = this.treeData[0].weight
      this.treeInfoTitle = this.treeData[0].label
      this.isRootNode = true
      this.isLeaf = false
    },
    handleNodeClick(data, node) {
      const labels = this.getAllParentLabels(node)
      this.treeInfoTitle = labels.join(' / ')
    },
    allowDrop(draggingNode, dropNode) {
      // 不能拖拽为根节点
      if (dropNode.level === 1) {
        return false
      }
      return true
    },
    getAllParentLabels(node) {
      const labels = []
      let currentNode = node
      while (currentNode.parent) {
        labels.unshift(currentNode.data.label)
        currentNode = currentNode.parent
      }
      return labels
    },
    setAttribute() {
      new this.$pageModal(
        setAttribute,
        {
          props: {
            attributes: this.attributes
          }
        },
        data => {
          data && (this.attributes = data)
        }
      )
    },
    onNodeSelected(node, data) {
      this.isRootNode = node.level == 1
      this.isAppend = false
      if (node.level == 1) {
        this.isLeaf = false
      } else {
        this.isLeaf = node.isLeaf
      }
      this.treeInfoData.name = data.label
      this.treeInfoData.tip = data.tip
      this.treeInfoData.weight = data.weight
      this.selectedId = data.id
    },
    save: _.debounce(async function () {
      const valid = await this.$refs.form.validate()
      if (!valid) return
      const newNode = {
        id: uuid.v1(),
        label: this.treeInfoData.name,
        tip: this.treeInfoData.tip,
        weight: this.treeInfoData.weight
      }
      // 根据父节点ID添加子节点
      if (this.isAppend) {
        addNodeToChildren(this.selectedId, this.isLeaf, this.treeData, newNode)
        this.$nextTick(() => {
          // this.$refs.tree.setCurrentKey(newNode.id)
          this.isAppend = false
          this.selectFirstNode()
        })
      } else {
        // 修改
        updateNode(this.selectedId, this.treeData, newNode, this.isLeaf)
      }
      this.isDirty = true
    }),
    append(node, data) {
      this.clearTreeInfoData()
      this.isAppend = true
      this.isRootNode = false
      this.selectedId = data.id
      this.isLeaf = node.isLeaf
    },
    clearTreeInfoData() {
      this.treeInfoData.name = ''
      this.treeInfoData.tip = ''
      this.treeInfoData.weight = 100
    },
    removeNodeById(treeData, nodeId) {
      return treeData.filter(node => {
        if (node.id !== nodeId) {
          if (node.children) {
            node.children = this.removeNodeById(node.children, nodeId)
          }
          return true // 保留当前节点
        }
        return false // 删除当前节点
      })
    },
    remove(node, data) {
      this.$confirm({ content: '确认删除?' })
        .then(async () => {
          this.treeData = this.removeNodeById(this.treeData, data.id)
          this.$nextTick(() => {
            this.selectFirstNode()
          })
          this.$message.success({
            content: '删除成功',
            duration: 2
          })
        })
        .catch(_ => _)
    }
  },
  created() {
    this.attributes = this.attr
  }
}
</script>

<style lang="less" scoped>
.formTree {
  display: flex;
  flex-direction: column;
  margin-top: 30px;
  height: 575px;
  .formSetting {
    display: flex;
    justify-content: space-between;
    .title {
      margin-top: -10px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      color: var(--primary-color);
      .block {
        width: 6px;
        height: 24px;
        background: var(--primary-color);
        margin-right: 6px;
      }
      .text {
        font-weight: 500;
        font-size: 16px;
      }
    }
  }
  .design {
    display: flex;
    height: 100%;
  }
}

.ivu-input-number, .el-input-number {
  width: 100%;
}
</style>